package ch.usi.inf.pf2.gui.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import ch.usi.inf.pf2.Sheet;
import ch.usi.inf.pf2.gui.JSpreadSheetGUI;
import ch.usi.inf.pf2.gui.SpreadSheetFileManager;

/**
 * Listener for the menu and button "Open"
 * 
 * @author Lorenzo Baracchi, Ebrisa Savina Mastrodicasa
 * 
 */
public class OpenActionListener implements ActionListener
{
    private static JFileChooser fileChooser = new JFileChooser(System
		  .getProperty("user.dir"));
    private JSpreadSheetGUI spreadTable;

    public OpenActionListener(JSpreadSheetGUI spreadTable)
    {
	   this.spreadTable = spreadTable;
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
	   int returnValue = fileChooser.showOpenDialog(spreadTable.getFrame());
	   if (returnValue != JFileChooser.APPROVE_OPTION)
	   {
		  return;
	   }
	   File selectedCSVFile = fileChooser.getSelectedFile();
	   Sheet selectedOpenFile = SpreadSheetFileManager
			 .openFile(selectedCSVFile.getName().replaceAll(".CSV", ""));
	   System.out.println(selectedCSVFile.getName());
	   if (selectedOpenFile == null)
	   {
		  JOptionPane
				.showMessageDialog(
					   spreadTable.getFrame(),
					   "The chosen file can not be opened. File format not recognized.",
					   "File Load Error", JOptionPane.ERROR_MESSAGE);
	   }
	   
	   spreadTable.getFrame().setVisible(false);
	   spreadTable = new JSpreadSheetGUI(selectedOpenFile);
    }

}
